<?php

namespace Api;

use Exception;
use Illuminate\Http\Response;
use Dingo\Api\Contract\Debug\MessageBagErrors;
use Illuminate\Contracts\Debug\ExceptionHandler as IlluminateExceptionHandler;
use Dingo\Api\Exception\Handler;

class ExceptionHandler extends Handler
{
    /**
     * Create a new exception handler instance.
     *
     * @param \Illuminate\Contracts\Debug\ExceptionHandler $parentHandler
     * @param array                                        $format
     * @param bool                                         $debug
     *
     * @return void
     */
    public function __construct(IlluminateExceptionHandler $parentHandler)
    {
        $this->parentHandler = $parentHandler;
        $this->format = [
            // 'code'    => ':code',
            'code'    => ':status_code',
            'message' => ':message',
            'errors'  => ':errors',
            'debug'   => ':debug',
        ];
        $this->debug = env('API_DEBUG', false);
    }

    /**
     * Prepare the replacements array by gathering the keys and values.
     *
     * @param \Exception $exception
     *
     * @return array
     */
    protected function prepareReplacements(Exception $exception)
    {
        $statusCode = $this->getStatusCode($exception);

        if (! $message = $exception->getMessage()) {
            $message = sprintf('%d %s', $statusCode, Response::$statusTexts[$statusCode]);
        }

        $replacements = [
            ':message' => $message,
            ':status_code' => $statusCode,
        ];

        if ($exception instanceof MessageBagErrors && $exception->hasErrors()) {
            $replacements[':errors'] = $exception->getErrors();
        }

        if ($code = $exception->getCode()) {
            // $replacements[':code'] = $code;
            $replacements[':status_code'] = $code;
        }

        if ($this->runningInDebugMode()) {
            $replacements[':debug'] = [
                'line' => $exception->getLine(),
                'file' => $exception->getFile(),
                'class' => get_class($exception),
                'trace' => explode("\n", $exception->getTraceAsString()),
            ];
        }

        return array_merge($replacements, $this->replacements);
    }
}
